<?php

namespace App\Http\Controllers\Strator;

// use App\Exports\OnTheJobExport;
use App\Http\Controllers\Controller;
use Illuminate\Database\Eloquent\Model;
use App\Models\Strator\StratorProduct;
use Illuminate\Http\Request;
// use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Support\Facades\DB;
use App\Models\Strator\StratorInventoryDetail;

class StratorProductController extends Controller
{
    protected Request $request;
    protected Model $model;

    public function __construct(Request $request,StratorProduct $strator)
    {
        $this->request=$request;
        $this->model = $strator;
    }

    /**
     * Display a listing of the resource.
     */
    public function inventory()
    {
        $perPage=$this->request->per_page??10;
        if($this->request->filled('search')){
            $search = $this->request->search;
            $list=$this->model
            ->modelSearch($this->request,$this->model)
            ->where('is_instore',1)
            ->where(function($query)use($search){
                $query->where('attr_name','like','%'.$search.'%')
                    ->orWhere('attr_name_fill','like','%'.$search.'%')
                    ->orWhere('name','like','%'.$search.'%')
                    ->orWhere('remark','like'.'%'.$search.'%')
                    ->orWhere('type_name','like','%'.$search.'%')
                    ->orWhere('type_name_fill','like','%'.$search.'%');
            })
            ->with(['type','attr'])
            ->orderByDesc('id')
            ->paginate($perPage);
        }else{
            $list=$this->model
            ->modelSearch($this->request,$this->model)
            ->where('is_instore',1)
            ->with(['type','attr'])
            ->orderByDesc('id')
            ->paginate($perPage);
        }
        $this->saveOperationLog('查询库存列表');
        return $this->success($list);
    }
    public function exportproduct()
    {
        $list = [];
        if($this->request->filled('search')){
            $search = $this->request->search;
            $data = $this->model->modelSearch($this->request,$this->model)->where(function($query)use($search){
                $query->where('attr_name','like','%'.$search.'%')
                    ->orWhere('attr_name_fill','like','%'.$search.'%')
                    ->orWhere('name','like','%'.$search.'%')
                    ->orWhere('remark','like'.'%'.$search.'%')
                    ->orWhere('type_name','like','%'.$search.'%')
                    ->orWhere('type_name_fill','like','%'.$search.'%');
            })->get();
        }else{
            $data = $this->model->modelSearch($this->request,$this->model)->get();
        }
        foreach ($data as $k=>$v){
            $list[$k]['name'] = $v->name;
            $list[$k]['type_name'] = $v->type_name;
            $list[$k]['attr_name_fill'] = $v->attr_name_fill.'-'.$v->attr_name;
            $list[$k]['inventory'] = $v->inventory;
            $list[$k]['cost_price'] = $v->cost_price;
            $list[$k]['cost_total'] = round($v->cost_price*$v->inventory,2);
            $list[$k]['warning'] = $v->warning;
        }
        $filename = '产品库存导出列表.xlsx';
        // $count = $data->count();
        // $header = ['产品名称','产品类型','产品属性','库存数量','单价', '库存货值', '库存预警值'];
        $header = '{"name":"产品名称","type_name":"产品类型","attr_name_fill":"产品属性","inventory":"库存数量","cost_price":"单价","cost_total":"库存货值","warning":"库存预警值"}';
        $this->saveOperationLog('导出产品库存');
        // return Excel::download(new OnTheJobExport($list,$header,$count),$filename);
        return $this->success(compact('list','header', 'filename'));
    }
    public function inventoryTotal()
    {
        if($this->request->filled('search')){
            $search = $this->request->search;
            $list=$this->model->modelSearch($this->request,$this->model)->where('is_instore',1)->where(function($query)use($search){
                $query->where('attr_name','like','%'.$search.'%')
                    ->orWhere('attr_name_fill','like','%'.$search.'%')
                    ->orWhere('name','like','%'.$search.'%')
                    ->orWhere('remark','like'.'%'.$search.'%')
                    ->orWhere('type_name','like','%'.$search.'%')
                    ->orWhere('type_name_fill','like','%'.$search.'%');
            })->get();
        }else{
            $list=$this->model->modelSearch($this->request,$this->model)->where('is_instore',1)->get();
        }
        $totalNum = $list->sum('inventory'); // 库存汇总
        $totalPrice = $list->sum(function ($item) {
            return $item->inventory * $item->cost_price;
        }); // 库存货值汇总
        return $this->success(compact('totalNum','totalPrice'));
    }

    /**
     * Display a listing of the resource.
     */
    public function warning()
    {
        $perPage=$this->request->per_page??10;
        $list=$this->model
            ->modelSearch($this->request,$this->model)
            ->where('is_instore',1)
            ->whereColumn('warning', '>=', 'inventory')
            ->with(['type','attr'])
            ->orderByDesc('id')
            ->paginate($perPage);
        $this->saveOperationLog('查询预警列表');
        return $this->success($list);
    }

    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $perPage=$this->request->per_page??10;
        $list=$this->model
            ->modelSearch($this->request,$this->model)
            // ->with(['type','attr', 'batchListAll'])
            // ->with(['batchListAll'])
            ->orderByDesc('id')
            ->paginate($perPage);
        $this->saveOperationLog('查询产品sku列表');
        return $this->success($list);
    }
    public function listall()
    {
        $list=DB::table('strator_product_alls')->whereNull('deleted_at')->get();
        return $this->success($list);
    }

    /**
     * Show the form for creating a new resource.干什么？
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store()
    {
        $data=$this->request->only($this->storeOnly());
        $this->model->fill($data);
        $this->model->save();
        $this->saveOperationLog('添加产品sku');
        return $this->success(['id'=>$this->model->id]);
    }
    //
    public function storeOnly():array{
        return [
            'type_id',
            'type_name',
            'type_name_fill',
            'diy_attr',
            'sort',
            'status',
            'attr_id',
            'attr_name',
            'attr_name_fill',
            'name',
            'images',
            'remark',
            'cost_price',
            'make_price',
            'sale_price',
            'wholesale_price',
        ];
    }

    /**
     * Display the specified resource.
     */
    public function show()
    {
//        return $this->success($this->request->user());
        $model=$this->model->findOrFail($this->request->id);
        return $this->success($model);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update()
    {
        $model=$this->model->findOrFail($this->request->id);
        $origin=$model->toArray();
        $data=$this->request->except($this->updateExcept());
        $model->fill($data);
        $model->save();
        $this->saveOperationLog('修改更新产品sku',$origin);
        return $this->successMsg();
    }
    //
    public function updateExcept():array
    {
        return [
            'id',
        ];
    }
    /**
     * Remove the specified resource from storage.
     */
    public function destroy()
    {
        $model=$this->model->findOrFail($this->request->id);
        $model->delete();
        $this->saveOperationLog('删除产品sku');
        return $this->successMsg('删除成功');
    }
    /**
     * Remove the specified resource from storage.
     * 获取批次号库存信息
     */
    public function getBatchList()
    {
        // $data=StratorInventoryDetail::query()->whereNotNull('share_contents')->get();
        $data=StratorInventoryDetail::query()->whereNotNull('share_contents')->whereColumn('quantity', '>', 'isused')->get();
        return $this->success($data);
    }
}
